package me.zhengjie.modules.system.rest;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.Log;
import me.zhengjie.domain.SysLog;
import me.zhengjie.modules.security.service.OnlineUserService;
import me.zhengjie.modules.security.service.dto.OnlineUserDto;
import me.zhengjie.modules.system.domain.*;
import me.zhengjie.modules.system.service.*;
import me.zhengjie.service.SysLogService;
import me.zhengjie.utils.SecurityUtils;
import me.zhengjie.utils.StringUtils;
import org.springframework.data.repository.query.Param;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequiredArgsConstructor
@Api(tags = "学校教材管理")
@RequestMapping("/api/statistics")
public class StatisticsController {

    private final UserService userService;

    private final ClazzService clazzService;

    private final ResourceService resourceService;

    private final QuestionService questionService;

    private final CourseService courseService;

    private final CourseandclazzService courseandclazzService;

    private final CourseandteachService courseandteachService;

    private final ClazzandstudentService clazzandstudentService;

    private final TeachService teachService;

    private final TeacherService teacherService;

    private final SysLogService sysLogService;

    private final MyteachService myteachService;

    private final UserquestionlogService userquestionlogService;

    private final ChapterlearnrecordService chapterlearnrecordService;

    private final TeachchapterService teachchapterService;

    private final TeachsubsectionService teachsubsectionService;

    private final StudentqaService studentqaService;

    private final StudentnoteService studentnoteService;

    private final StudentsignService studentsignService;

    private final OnlineUserService onlineUserService;

    private final UserexercisesetlogService userexercisesetlogService;
    //学生统计

    //每本教材答题正确率 列表
    @GetMapping("/getStudentAccuracy")
    @Log("查询学生每本教材答题正确率")
    @ApiOperation("查询学生每本教材答题正确率")
    public ResponseEntity<Object> getStudentAccuracy(){

        List<Map<String,String>> maps = getStudentQuestionNum();
        for(Map<String,String> map:maps){
            float accuracy = Float.parseFloat(map.get("correctNum"))/Float.parseFloat(map.get("questionNum"));
            map.put("accuracy",String.valueOf(accuracy));
        }
        return new ResponseEntity<>(maps, HttpStatus.OK);
    }

    //学生自己的活跃度 近一周7 近一月 近半年
    @GetMapping("/getStudentActive")
    @Log("查询学生自己的活跃度")
    @ApiOperation("查询学生自己的活跃度")
    public ResponseEntity<Object> getStudentActive(@Param("type") Integer type){
        LocalDateTime startOfDay = null;
        if(type == 1){
            startOfDay = LocalDateTime.now().minusDays(7).withHour(0).withMinute(0).withSecond(0).withNano(0);
        } else if(type == 2){
            startOfDay = LocalDateTime.now().minusDays(30).withHour(0).withMinute(0).withSecond(0).withNano(0);
        } else if(type == 3){
            startOfDay = LocalDateTime.now().minusDays(180).withHour(0).withMinute(0).withSecond(0).withNano(0);
        }


        LocalDateTime endOfDay = LocalDateTime.now().withHour(23).withMinute(59).withSecond(59).withNano(999999999);

        // 转换为Timestamp
        Timestamp startTimestamp = Timestamp.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
        Timestamp endTimestamp = Timestamp.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",SecurityUtils.getCurrentUserId());
        queryWrapper.lt("createTime",endTimestamp);
        queryWrapper.ge("createTime",startTimestamp);
        queryWrapper.eq("description","用户登录");
        List<SysLog> sysLogList = sysLogService.list(queryWrapper);
        List<Timestamp> timestamps = new ArrayList<>();
        if(type == 1){
            timestamps = generateDailyTimestamps(6);
        } else if(type == 2){
            timestamps = generateDailyTimestamps(29);
        } else if(type == 3){
            timestamps = generateDailyTimestamps(181);
        }

        List<Integer> list = new ArrayList<>();
        for(Timestamp timestamp:timestamps){
            Integer count = 0;

            for(SysLog sysLog:sysLogList){

                if(Objects.equals(String.valueOf(timestamp).substring(0, 10), String.valueOf(sysLog.getCreateTime()).substring(0, 10))){

                    count = count + 1;


                }
            }

            list.add(count);

        }
        Map<String,List> map = new HashMap<>();
        map.put("list",list);
        map.put("timestamp",timestamps);
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

    //学生每本教材的试题答对占比
    @GetMapping("/getStudentQuestionRatio")
    @Log("学生每本教材的试题答对占比")
    @ApiOperation("学生每本教材的试题答对占比")
    public ResponseEntity<Object> getStudentQuestionRatio(){
        //获取学生用户拥有的教材
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",SecurityUtils.getCurrentUserId());
        List<Myteach> myteachList = myteachService.list(queryWrapper);
        List<Integer> teachIds = new ArrayList<>();
        for(Myteach myteach:myteachList){
            teachIds.add(myteach.getTeachId());
        }
        //获取用户教材所作的试题
        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("userId",SecurityUtils.getCurrentUserId());
        queryWrapper1.in("teachId",teachIds);
        List<Userquestionlog> userquestionlogList = new ArrayList<>();

        //获取教材
        List<Teach> teachList = new ArrayList<>();
        List<Map<String,String>> maps = new ArrayList<>();
        if(!teachIds.isEmpty()){
            teachList = teachService.listByIds(teachIds);
            for(Teach teach:teachList){
                Map<String,String> map = new HashMap<>();
                map.put("id",String.valueOf(teach.getId()));
                map.put("name",teach.getName());
                map.put("singleNum","0");
                map.put("multipleNum","0");
                map.put("judgeNum","0");
                map.put("completionNum","0");
                map.put("shortNum","0");
                map.put("questionNum","0");
                maps.add(map);
            }
            userquestionlogList = userquestionlogService.list(queryWrapper1);

            for(Userquestionlog userquestionlog:userquestionlogList){
                for(Map<String,String> map:maps){
                    if(Integer.parseInt(map.get("id")) == Math.toIntExact(userquestionlog.getTeachid())){
                        if(userquestionlog.getType() == 0){
                            Integer currentNum =  Integer.parseInt(map.get("singleNum")) + 1;
                            map.put("singleNum", String.valueOf(currentNum));
                        } else if(userquestionlog.getType() == 1){
                            Integer currentNum =  Integer.parseInt(map.get("multipleNum")) + 1;
                            map.put("multipleNum", String.valueOf(currentNum));

                        } else if(userquestionlog.getType() == 2){
                            Integer currentNum =  Integer.parseInt(map.get("judgeNum")) + 1;
                            map.put("judgeNum", String.valueOf(currentNum));

                        } else if(userquestionlog.getType() == 3){
                            Integer currentNum =  Integer.parseInt(map.get("completionNum")) + 1;
                            map.put("completionNum", String.valueOf(currentNum));

                        } else if(userquestionlog.getType() == 4){
                            Integer currentNum =  Integer.parseInt(map.get("shortNum")) + 1;
                            map.put("shortNum", String.valueOf(currentNum));

                        }
                        Integer num =  Integer.parseInt(map.get("questionNum")) + 1;;
                        map.put("questionNum",String.valueOf(num));
                    }
                }
            }
        }
        return new ResponseEntity<>(maps, HttpStatus.OK);
    }
    //获取学生错题统计
    @GetMapping("/getErrorQuestionList")
    @Log("查询学生错题列表")
    @ApiOperation("查询学生错题列表")
    public ResponseEntity<Object> getErrorQuestionList(){
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",SecurityUtils.getCurrentUserId());
        queryWrapper.eq("isTrue",0);
        List<Userquestionlog> userquestionlogList = userquestionlogService.list(queryWrapper);
        List<Integer> questionList = new ArrayList<>();
        List<Question> questionList1 = new ArrayList<>();
        if(!userquestionlogList.isEmpty()){

            for(Userquestionlog userquestionlog:userquestionlogList){
                questionList.add(Math.toIntExact(userquestionlog.getQuestionid()));
            }
            questionList1 = questionService.listByIds(questionList);
        }


        return new ResponseEntity<>(questionList1, HttpStatus.OK);
    }

    //教师统计 三天 七天 一个月
    //教师活跃度（创建的班级的学生的活跃度）
    @GetMapping("/getClassStudentActives")
    @Log("查询教师活跃度（创建的班级的学生的活跃度）")
    @ApiOperation("查询教师活跃度（创建的班级的学生的活跃度）")
    public ResponseEntity<Object> getClassStudentActives(@Param("type") Integer type){

        LocalDateTime startOfDay = null;
        if(type == 1){
            startOfDay = LocalDateTime.now().minusDays(7).withHour(0).withMinute(0).withSecond(0).withNano(0);
        } else if(type == 2){
            startOfDay = LocalDateTime.now().minusDays(30).withHour(0).withMinute(0).withSecond(0).withNano(0);
        } else if(type == 3){
            startOfDay = LocalDateTime.now().minusDays(180).withHour(0).withMinute(0).withSecond(0).withNano(0);
        }


        LocalDateTime endOfDay = LocalDateTime.now().withHour(23).withMinute(59).withSecond(59).withNano(999999999);

        // 转换为Timestamp
        Timestamp startTimestamp = Timestamp.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
        Timestamp endTimestamp = Timestamp.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());

        List<Integer> clazzIds = getClazzIds();

        //获取学生id
        List<Clazzandstudent> classStudentList = new ArrayList<>();
        List<Integer> studentIds = new ArrayList<>();
        QueryWrapper queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.in("clazzId",clazzIds);

        if(!clazzIds.isEmpty()){
            classStudentList = clazzandstudentService.list(queryWrapper2);
            for(Clazzandstudent clazzandstudent:classStudentList){
                studentIds.add(Math.toIntExact(clazzandstudent.getUserId()));
            }
        }

        QueryWrapper queryWrapper = new QueryWrapper();

        queryWrapper.lt("createTime",endTimestamp);
        queryWrapper.ge("createTime",startTimestamp);
        queryWrapper.in("userId",studentIds);
        List<SysLog> sysLogList = new ArrayList<>();
        if(!studentIds.isEmpty()){
            sysLogList = sysLogService.list(queryWrapper);
        }


        List<Timestamp> timestamps = new ArrayList<>();
        if(type == 1){
            timestamps = generateDailyTimestamps(6);
        } else if(type == 2){
            timestamps = generateDailyTimestamps(29);
        } else if(type == 3){
            timestamps = generateDailyTimestamps(181);
        }
        List<Integer> list = new ArrayList<>();
        for(Timestamp timestamp:timestamps){
            List<Integer> list1 =new ArrayList<>();

            for(SysLog sysLog:sysLogList){

                if(Objects.equals(String.valueOf(timestamp).substring(0, 10), String.valueOf(sysLog.getCreateTime()).substring(0, 10))){
                    if(!containsElement(list1,Math.toIntExact(sysLog.getUserId()))){
                        list1.add(Math.toIntExact(sysLog.getUserId()));
                    }

                }
            }
            list.add(list1.size());

        }
        Map<String,List> map = new HashMap<>();
        map.put("list",list);
        map.put("timestamp",timestamps);
        return new ResponseEntity<>(map, HttpStatus.OK);
    }
    //教材学习人数 一周日期

    //教师创建课程中每个班级的总人数和在线人数
    @GetMapping("/getStudentTotalAndStudyNum")
    @Log("查询教师创建课程中每个班级的总人数和在线人数")
    @ApiOperation("查询教师创建课程中每个班级的总人数和在线人数")
    public ResponseEntity<Object> getStudentTotalAndStudyNum(){

        List<OnlineUserDto> userDtoList = onlineUserService.getAll(null);
        List<Integer> clazzIds = getClazzIds();

        QueryWrapper queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.in("clazzId",clazzIds);

        List<ClassStudentCount> classStudentCountList = new ArrayList<>();
        List<Clazzandstudent> classStudentList = new ArrayList<>();
//        List<Integer> userIds = new ArrayList<>();
        if(!clazzIds.isEmpty()){
//
            classStudentList = clazzandstudentService.list(queryWrapper2);

            for(Clazzandstudent clazzandstudent:classStudentList){
//                userIds.add(Math.toIntExact(clazzandstudent.getUserId()));
                ClassStudentCount classStudentCount = new ClassStudentCount();
                Integer status = 0;
                for(ClassStudentCount classStudentCount1:classStudentCountList){
                    if(classStudentCount1.getId() == Math.toIntExact(clazzandstudent.getClazzId())){
                        status = 1;
                        if(classStudentCount.getCount()!=null){
                            classStudentCount.setCount(classStudentCount.getCount()+1);
                        } else {
                            classStudentCount.setCount(1);
                        }

                    }
                }
                if(status == 0){
                    classStudentCount.setCount(1);
                    classStudentCount.setId(Math.toIntExact(clazzandstudent.getClazzId()));
                    classStudentCountList.add(classStudentCount);
                }

            }

            List<Clazz> clazzList = clazzService.listByIds(clazzIds);
            for(Clazz clazz:clazzList){
                for(ClassStudentCount classStudentCount1:classStudentCountList){
                    if(classStudentCount1.getId() == Math.toIntExact(clazz.getId())){
                        classStudentCount1.setName(clazz.getName());
                    }
                }
            }

            List<String> onlineUserArr = new ArrayList<>();
            List<Integer> onlineUserIdArr = new ArrayList<>();


            List<Clazzandstudent> clazzandstudentList = new ArrayList<>();
            for(OnlineUserDto onlineUserDto:userDtoList){
                onlineUserArr.add(onlineUserDto.getUserName());

            }


            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.in("username",onlineUserArr);
            List<User> userList = new ArrayList<>();
            if(!onlineUserArr.isEmpty()){
                userList = userService.list(queryWrapper);
            }
            for(User user:userList){
                onlineUserIdArr.add(Math.toIntExact(user.getId()));
            }

            QueryWrapper queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.in("userId",onlineUserIdArr);
            clazzandstudentList = clazzandstudentService.list(queryWrapper1);

            for(ClassStudentCount classStudentCount:classStudentCountList){
                classStudentCount.setOnlineCount(0);
                for(Clazzandstudent clazzandstudent:clazzandstudentList){
                    if(classStudentCount.getId() == Math.toIntExact(clazzandstudent.getClazzId())){

                        classStudentCount.setOnlineCount(classStudentCount.getOnlineCount()+1);
                    }
                }
            }
        }
        return new ResponseEntity<>(classStudentCountList, HttpStatus.OK);
    }

    //查询教材学习人数
    @GetMapping("/getTeachUserCount")
    @Log("查询教材学习人数")
    @ApiOperation("查询教材学习人数")
    public ResponseEntity<List<Map<String,String>>> getTeachUserCount(){
        List<Integer> courseIds = getCourseIds();

        List<Courseandteach> courseandteachList = new ArrayList<>();
//        List<Courseandclazz> courseandclazzList =new ArrayList<>();
        List<Integer> teachIds = new ArrayList<>();
        if(!courseIds.isEmpty()){
            QueryWrapper queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.in("courseId",courseIds);
            courseandteachList = courseandteachService.list(queryWrapper3);

//            QueryWrapper queryWrapper4 = new QueryWrapper<>();
//            queryWrapper4.in("courseId",courseIds);
//            courseandclazzList = courseandclazzService.list(queryWrapper4);
            for(Courseandteach courseandteach:courseandteachList){
                teachIds.add(Math.toIntExact(courseandteach.getTeachid()));
            }
        }
        List<Map<String,String>> maps = new ArrayList<>();

        if(!teachIds.isEmpty()){
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.in("teachId",teachIds);
            List<Chapterlearnrecord> chapterlearnrecordList = chapterlearnrecordService.list(queryWrapper);

            QueryWrapper queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.in("id",teachIds);
            List<Teach> teachList = teachService.list(queryWrapper1);

            for(Teach teach:teachList){
                Map<String,String> map = new HashMap<>();
                map.put("id", String.valueOf(teach.getId()));
                map.put("name", teach.getName());
                List<Integer> userIds = new ArrayList<>();
                for(Chapterlearnrecord chapterlearnrecord:chapterlearnrecordList){
                    if(chapterlearnrecord.getTeachId() == teach.getId()){
                        if(!containsElement(userIds, Math.toIntExact(chapterlearnrecord.getUserId()))){
                            userIds.add(Math.toIntExact(chapterlearnrecord.getUserId()));
                        }
                    }
                }
                map.put("num",String.valueOf(userIds.size()));
                maps.add(map);
            }


        }


        return new ResponseEntity<>(maps, HttpStatus.OK);
    }

    //统计用户总数、电子教材数、资源总数、试题总数
    @GetMapping("/getCountObj")
    @Log("查询数量统计信息")
    @ApiOperation("查询数量统计信息")
    public ResponseEntity<Map<String,Object>> getCountObj(){

        Map<String,Object> map = new HashMap<>();

        List<Integer> courseIds = getCourseIds();

        List<Integer> clazzIds = getClazzIds();


        List<OnlineUserDto> userDtoList = onlineUserService.getAll(null);
        //根据班级获取用户数量数量
        QueryWrapper queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.in("clazzId",clazzIds);

        List<Long> userIdList = new ArrayList<>();
        List<Clazzandstudent> classstudent = new ArrayList<>();
        if(!clazzIds.isEmpty()){

            List<String> onlineUserArr = new ArrayList<>();


            List<Clazzandstudent> clazzandstudentList = new ArrayList<>();
            for(OnlineUserDto onlineUserDto:userDtoList){
                onlineUserArr.add(onlineUserDto.getUserName());

            }
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.in("username",onlineUserArr);
            List<User> userList = new ArrayList<>();
            if(!onlineUserArr.isEmpty()){
                userList = userService.list(queryWrapper);
            }

            classstudent = clazzandstudentService.list(queryWrapper2);


            for(Clazzandstudent clazzandstudent:classstudent){

                for(User user:userList){
                    if(user.getId() == clazzandstudent.getUserId()){
                        userIdList.add(user.getId());
                    }
                }
            }


        }

        map.put("studentCount",userIdList.size());

        //根据课程获取任课教材数量
        QueryWrapper queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.in("courseId",courseIds);
        Long teachCount = 0L;

        if(!courseIds.isEmpty()){
            teachCount = courseandteachService.count(queryWrapper3);
        }
        map.put("teachCount",teachCount);

        //获取创建试题数量
        QueryWrapper queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.eq("userId",SecurityUtils.getCurrentUserId());
        Teacher teacher = teacherService.getOne(queryWrapper4);

        QueryWrapper queryWrapper5 = new QueryWrapper<>();
        Long questionCount = 0L;
        if(teacher!=null){
            queryWrapper5.eq("teacherId",teacher.getId());
            questionCount = questionService.count(queryWrapper5);
        }
        map.put("questionCount",questionCount);

        //获取资源数量
        QueryWrapper queryWrapper6 = new QueryWrapper<>();
        queryWrapper6.eq("createUserId",SecurityUtils.getCurrentUserId());
        Long resourceCount = resourceService.count(queryWrapper6);
        map.put("resourceCount",resourceCount);
        return new ResponseEntity<>(map, HttpStatus.OK);
    }



    //获取教材统计
    //获取开课班级列表
    @GetMapping("/getClassList")
    @Log("查询开课班级列表")
    @ApiOperation("查询开课班级列表")
    public ResponseEntity<Object> getClassList(@Param("QueryActive")  QueryActive queryActive){

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.in("teachId",queryActive.getTeachId());
        List<Courseandteach>  courseandteachList = courseandteachService.list(queryWrapper);

        List<Integer> courseIds = new ArrayList<>();
        for(Courseandteach courseandteach:courseandteachList){
            courseIds.add(Math.toIntExact(courseandteach.getCourseid()));
        }

        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.in("courseId",courseIds);
        List<Courseandclazz> courseandclazzList = courseandclazzService.list(queryWrapper1);
        List<Integer> clazzIds = new ArrayList<>();
        for(Courseandclazz courseandclazz:courseandclazzList){
            clazzIds.add(Math.toIntExact(courseandclazz.getClazzId()));
        }
        QueryWrapper queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.in("id",clazzIds);
        List<Clazz> clazzList = clazzService.list(queryWrapper2);
        return new ResponseEntity<>(clazzList, HttpStatus.OK);
    }

    //获取教材信息以及教材活跃数量
    @GetMapping("/getTeachMsgAndActiveNum")
    @Log("查询教材信息以及教材活跃数量")
    @ApiOperation("查询教材信息以及教材活跃数量")
    public ResponseEntity<Object> getTeachMsgAndActiveNum(@Param("QueryActive")  QueryActive queryActive){

//        LocalDateTime startOfDay = null;
//        if(queryActive.getType() == 1){
        LocalDateTime  startOfDay1 = LocalDateTime.now().minusDays(7).withHour(0).withMinute(0).withSecond(0).withNano(0);
//        } else if(queryActive.getType() == 2){
        LocalDateTime      startOfDay2 = LocalDateTime.now().minusDays(30).withHour(0).withMinute(0).withSecond(0).withNano(0);
//        } else if(queryActive.getType() == 3){
        LocalDateTime    startOfDay3 = LocalDateTime.now().minusDays(181).withHour(0).withMinute(0).withSecond(0).withNano(0);
//        }


        LocalDateTime endOfDay = LocalDateTime.now().withHour(23).withMinute(59).withSecond(59).withNano(999999999);

        // 转换为Timestamp
        Timestamp startTimestamp = Timestamp.from(startOfDay1.atZone(ZoneId.systemDefault()).toInstant());
        Timestamp startTimestamp2 = Timestamp.from(startOfDay2.atZone(ZoneId.systemDefault()).toInstant());
        Timestamp startTimestamp3 = Timestamp.from(startOfDay3.atZone(ZoneId.systemDefault()).toInstant());
        Timestamp endTimestamp = Timestamp.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());

        //获取教材
        Teach teach = teachService.getById(queryActive.getTeachId());

        //获取班级id
        //获取三天 一周 一个月的 学习人数
        //根据班级获取用户数量数量
        QueryWrapper queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("clazzId",queryActive.getClazzId());
        List<Clazzandstudent> clazzandstudentList = clazzandstudentService.list(queryWrapper2);
        List<Integer> studentUserId = new ArrayList<>();
        for(Clazzandstudent clazzandstudent:clazzandstudentList){
            studentUserId.add(Math.toIntExact(clazzandstudent.getUserId()));
        }

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",studentUserId);
        queryWrapper.eq("teachId",teach.getId());
        queryWrapper.lt("startTime",endTimestamp);
        queryWrapper.ge("startTime",startTimestamp3);

        List<Chapterlearnrecord> chapterlearnrecordList = chapterlearnrecordService.list(queryWrapper);
        List<Timestamp> timestamps = new ArrayList<>();

        List<Timestamp> timestamps2 = new ArrayList<>();

        List<Timestamp> timestamps3 = new ArrayList<>();
//        if(queryActive.getType() == 1){
            timestamps = generateDailyTimestamps(6);
//        } else if(queryActive.getType() == 2){
            timestamps2 = generateDailyTimestamps(29);
//        } else if(queryActive.getType() == 3){
            timestamps3 = generateDailyTimestamps(180);
//        }
        List<Integer> list1 = new ArrayList<>();
        for(Timestamp timestamp:timestamps){
            List<Integer> list2 = new ArrayList<>();

            Date date1 = new Date(timestamp.getTime());
            for(Chapterlearnrecord chapterlearnrecord:chapterlearnrecordList){
                Date date2 = new Date(chapterlearnrecord.getStartTime().getTime());
                if(date1 == date2){
                    if(!containsElement(list2,Math.toIntExact(chapterlearnrecord.getUserId()))){
                        list2.add(Math.toIntExact(chapterlearnrecord.getUserId()));
                    }
                }
            }
            list1.add(list2.size());
        }

        List<Integer> list3 = new ArrayList<>();
        for(Timestamp timestamp:timestamps2){
            List<Integer> list2 = new ArrayList<>();

            Date date1 = new Date(timestamp.getTime());
            for(Chapterlearnrecord chapterlearnrecord:chapterlearnrecordList){
                Date date2 = new Date(chapterlearnrecord.getStartTime().getTime());
                if(date1 == date2){
                    if(!containsElement(list2,Math.toIntExact(chapterlearnrecord.getUserId()))){
                        list2.add(Math.toIntExact(chapterlearnrecord.getUserId()));
                    }
                }
            }
            list3.add(list2.size());
        }

        List<Integer> list4 = new ArrayList<>();
        for(Timestamp timestamp:timestamps3){
            List<Integer> list2 = new ArrayList<>();

            Date date1 = new Date(timestamp.getTime());
            for(Chapterlearnrecord chapterlearnrecord:chapterlearnrecordList){
                Date date2 = new Date(chapterlearnrecord.getStartTime().getTime());
                if(date1 == date2){
                    if(!containsElement(list2,Math.toIntExact(chapterlearnrecord.getUserId()))){
                        list2.add(Math.toIntExact(chapterlearnrecord.getUserId()));
                    }
                }
            }
            list4.add(list2.size());
        }


        Map<String,String> map = new HashMap<>();
        map.put("id", String.valueOf(teach.getId()));
        map.put("name", teach.getName());
        map.put("weekNum", String.valueOf(list1.size()));
        map.put("monthNum", String.valueOf(list3.size()));
        map.put("yearNum", String.valueOf(list4.size()));
        map.put("studentNum", String.valueOf(studentUserId.size()));
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

    //教材 班级一周活跃统计
    @GetMapping("/getWeekActiveStatistics")
    @Log("查询教材班级一周活跃统计")
    @ApiOperation("查询教材班级一周活跃统计")
    public ResponseEntity<Object> getWeekActiveStatistics(@Param("QueryActive")  QueryActive queryActive){

        LocalDateTime startOfDay = LocalDateTime.now().minusDays(7).withHour(0).withMinute(0).withSecond(0).withNano(0);


        LocalDateTime endOfDay = LocalDateTime.now().withHour(23).withMinute(59).withSecond(59).withNano(999999999);

        // 转换为Timestamp
        Timestamp startTimestamp = Timestamp.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
        Timestamp endTimestamp = Timestamp.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());

        //获取教材
        Teach teach = teachService.getById(queryActive.getTeachId());

        //根据班级获取用户数量数量
        QueryWrapper queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("clazzId",queryActive.getClazzId());
        List<Clazzandstudent> clazzandstudentList = clazzandstudentService.list(queryWrapper2);
        List<Integer> studentUserId = new ArrayList<>();
        for(Clazzandstudent clazzandstudent:clazzandstudentList){
            studentUserId.add(Math.toIntExact(clazzandstudent.getUserId()));
        }

        //根据教材查询一周活跃
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.in("userId",studentUserId);
        queryWrapper.eq("teachId",teach.getId());
        queryWrapper.lt("startTime",endTimestamp);
        queryWrapper.ge("startTime",startTimestamp);

        List<Chapterlearnrecord> chapterlearnrecordList = chapterlearnrecordService.list(queryWrapper);
        List<Timestamp> timestamps = generateDailyTimestamps(7);

        List<Integer> list1 = new ArrayList<>();
        for(Timestamp timestamp:timestamps){
            List<Integer> list2 = new ArrayList<>();
            for(Chapterlearnrecord chapterlearnrecord:chapterlearnrecordList){
                if(Objects.equals(String.valueOf(timestamp).substring(0, 10), String.valueOf(chapterlearnrecord.getStartTime()).substring(0, 10))){
                    if(!containsElement(list2,Math.toIntExact(chapterlearnrecord.getUserId()))){
                        list2.add(Math.toIntExact(chapterlearnrecord.getUserId()));
                    }
                }
            }
            list1.add(list2.size());
        }
        return new ResponseEntity<>(list1, HttpStatus.OK);
    }

    //班级 教材章节统计
    @GetMapping("/getTeachChapterStatistics")
    @Log("查询班级教材章节统计")
    @ApiOperation("查询班级教材章节统计")
    public ResponseEntity<Object> getTeachChapterStatistics(@Param("QueryActive")  QueryActive queryActive){


        //获取班级学生
        QueryWrapper queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.eq("clazzId",queryActive.getClazzId());
        List<Clazzandstudent> clazzandstudentList = clazzandstudentService.list(queryWrapper4);
        List<Integer> userIds = new ArrayList<>();
        for(Clazzandstudent clazzandstudent:clazzandstudentList){
            userIds.add(Math.toIntExact(clazzandstudent.getUserId()));
        }
        //根据教材插叙章节学习进度统计
        //每个章节学习人数 测试数 提问数 笔记数 标记数
//        Teach teach = teachService.getById(queryActive.getTeachId());
        List<Map<String,String>> maps = new ArrayList<>();
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teachId",queryActive.getTeachId());
        List<Teachchapter> teachchapterList = teachchapterService.list(queryWrapper);
        List<Integer> teachchapterIds = new ArrayList<>();
        for(Teachchapter teachchapter:teachchapterList){
            teachchapterIds.add(Math.toIntExact(teachchapter.getId()));
        }

        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("teachId",queryActive.getTeachId());
        List<Teachsubsection> teachsubsectionList = teachsubsectionService.list(queryWrapper1);

        List<Integer> teachsubsectionIds = new ArrayList<>();
        for(Teachsubsection teachsubsection:teachsubsectionList){
            teachsubsectionIds.add(Math.toIntExact(teachsubsection.getId()));
        }
        List<Map<String,String>> maps1 = new ArrayList<>();
        List<Map<String,String>> maps2 = new ArrayList<>();

        QueryWrapper queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.in("teachChapterId",teachchapterIds);
        queryWrapper2.isNull("teachSubsectionId");
        queryWrapper2.in("userId",userIds);
        //获取章
        List<Chapterlearnrecord> chapterlearnrecordList = new ArrayList<>();
        if(!userIds.isEmpty() && !teachchapterIds.isEmpty()){
            chapterlearnrecordList = chapterlearnrecordService.list(queryWrapper2);

            System.out.println("==chapterlearnrecordList=="+chapterlearnrecordList);
        }

        //获取小节
        QueryWrapper queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.in("teachSubsectionId",teachsubsectionIds);
        queryWrapper3.in("userId",userIds);
        List<Chapterlearnrecord> chapterlearnrecordList2 = new ArrayList<>();
        if(!teachsubsectionIds.isEmpty() && !userIds.isEmpty()){
            chapterlearnrecordList2 = chapterlearnrecordService.list(queryWrapper3);
        }


        //小节笔记数
        QueryWrapper queryWrapper5 = new QueryWrapper<>();
        queryWrapper5.in("teachSubsectionId",teachsubsectionIds);
        queryWrapper5.in("createUserId",userIds);

        List<Studentnote> studentnoteList = new ArrayList<>();
        if(!userIds.isEmpty() && !teachsubsectionIds.isEmpty()){
            studentnoteList = studentnoteService.list(queryWrapper5);
        }
        //章节笔记数
        QueryWrapper queryWrapper6 = new QueryWrapper<>();
        queryWrapper6.in("teachChapterId",teachchapterIds);
        queryWrapper6.eq("teachSubsectionId",null);
        queryWrapper6.in("createUserId",userIds);
        List<Studentnote> studentnoteList1 = new ArrayList<>();
        if(!teachchapterIds.isEmpty() && !userIds.isEmpty()){
            studentnoteList1 = studentnoteService.list(queryWrapper6);
        }

        //小节提问数
        QueryWrapper queryWrapper7 = new QueryWrapper<>();
        queryWrapper7.in("teachSubsectionId",teachsubsectionIds);
        queryWrapper7.in("userId",userIds);
        List<Studentqa> studentqaList = new ArrayList<>();
        if(!userIds.isEmpty() && !teachsubsectionIds.isEmpty()){
            studentqaList = studentqaService.list(queryWrapper5);

        }
        //章节提问数
        QueryWrapper queryWrapper8 = new QueryWrapper<>();
        queryWrapper8.in("teachChapterId",teachchapterIds);
        queryWrapper8.eq("teachSubsectionId",null);
        queryWrapper8.in("createUserId",userIds);
        List<Studentqa> studentqaList1 = new ArrayList<>();
        if(!teachchapterIds.isEmpty() && !userIds.isEmpty()){
            studentqaList1 = studentnoteService.list(queryWrapper8);
        }

        //小节标记数
        QueryWrapper queryWrapper9 = new QueryWrapper<>();
        queryWrapper9.in("teachSubsectionId",teachsubsectionIds);
        queryWrapper9.in("createUserId",userIds);
        List<Studentsign> studentsignList = new ArrayList<>();
        if(!userIds.isEmpty() && !teachsubsectionIds.isEmpty()){
            studentsignList = studentsignService.list(queryWrapper9);
        }

        //章节标记数
        QueryWrapper queryWrapper10 = new QueryWrapper<>();
        queryWrapper10.in("teachChapterId",teachchapterIds);
        queryWrapper10.eq("teachSubsectionId",null);
        queryWrapper10.in("createUserId",userIds);
        List<Studentsign> studentsignList1 = new ArrayList<>();
        if(!userIds.isEmpty() && !teachchapterIds.isEmpty()){
            studentsignService.list(queryWrapper10);
        }

        for(Teachchapter teachchapter:teachchapterList){
            Map<String,String> map = new HashMap<>();
            map.put("id", String.valueOf(teachchapter.getId()));
            map.put("name",teachchapter.getName());
            map.put("type","0");
            map.put("studentNum","0");

            if(!chapterlearnrecordList.isEmpty()){
                for(Chapterlearnrecord chapterlearnrecord:chapterlearnrecordList){
                    if(teachchapter.getId() == chapterlearnrecord.getTeachChapterId()){
                        map.put("studentNum",String.valueOf(Integer.valueOf(map.get("studentNum")) + 1));
                    }
                }
            }


            map.put("noteNum","0");
            if(!studentnoteList1.isEmpty()){
                for(Studentnote studentnote:studentnoteList1){
                    if(Math.toIntExact(teachchapter.getId()) == studentnote.getTeachChapterId()){
                        map.put("noteNum",String.valueOf(Integer.valueOf(map.get("noteNum")) + 1));
                    }
                }
            }


            map.put("qaNum","0");
            if(!studentqaList1.isEmpty()){
                for(Studentqa studentqa:studentqaList1){
                    if(Math.toIntExact(teachchapter.getId()) == studentqa.getTeachChapterId()){
                        map.put("qaNum",String.valueOf(Integer.valueOf(map.get("qaNum")) + 1));
                    }
                }
            }


            map.put("signNum","0");
            if(!studentsignList1.isEmpty()){
                for(Studentsign studentsign:studentsignList1){
                    if(Math.toIntExact(teachchapter.getId()) == studentsign.getTeachChapterId()){
                        map.put("signNum",String.valueOf(Integer.valueOf(map.get("signNum")) + 1));
                    }
                }
            }

            maps1.add(map);
        }

        for(Teachsubsection teachsubsection:teachsubsectionList){
            Map<String,String> map = new HashMap<>();
            map.put("id", String.valueOf(teachsubsection.getId()));
            map.put("name",teachsubsection.getName());
            map.put("type","1");
            map.put("teachChapterId", String.valueOf(teachsubsection.getTeachchapterid()));
            map.put("studentNum","0");

            if(!chapterlearnrecordList2.isEmpty()){
                for(Chapterlearnrecord chapterlearnrecord:chapterlearnrecordList2){
                    if(teachsubsection.getId() == chapterlearnrecord.getTeachChapterId()){
                        map.put("studentNum",String.valueOf(Integer.valueOf(map.get("studentNum")) + 1));
                    }
                }
            }


            map.put("noteNum","0");
            if(!studentnoteList.isEmpty()){
                for(Studentnote studentnote:studentnoteList){
                    if(Math.toIntExact(teachsubsection.getId()) == studentnote.getTeachChapterId()){
                        map.put("noteNum",String.valueOf(Integer.valueOf(map.get("noteNum")) + 1));
                    }
                }
            }


            map.put("qaNum","0");
            if(!studentqaList.isEmpty()){
                for(Studentqa studentqa:studentqaList){
                    if(Math.toIntExact(teachsubsection.getId()) == studentqa.getTeachChapterId()){
                        map.put("qaNum",String.valueOf(Integer.valueOf(map.get("qaNum")) + 1));
                    }
                }
            }


            map.put("signNum","0");
            for(Studentsign studentsign:studentsignList){
                if(Math.toIntExact(teachsubsection.getId()) == studentsign.getTeachChapterId()){
                    map.put("signNum",String.valueOf(Integer.valueOf(map.get("signNum")) + 1));
                }
            }
            maps2.add(map);
        }
        for(Map<String,String> map:maps2){
            maps1.add(map);
        }

//        private final StudentqaService studentqaService;
//
//        private final StudentnoteService studentnoteService;
//
//        private final StudentsignService studentsignService;
        return new ResponseEntity<>(maps1, HttpStatus.OK);
    }

    //获取教材班级学生学习情况
    @GetMapping("/getTeachClazzStudySituation")
    @Log("获取教材班级学生学习情况")
    @ApiOperation("获取教材班级学生学习情况")
    public ResponseEntity<Object> getTeachClazzStudySituation(@Param("QueryActive") QueryActive queryActive){

        System.out.println("====queryActive====="+queryActive);
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("clazzId",queryActive.getClazzId());
        List<Clazzandstudent> clazzandstudentList = clazzandstudentService.list(queryWrapper);
        List<Integer> userIds = new ArrayList<>();
        List<Map<String,String>> maps = new ArrayList<>();

        if(!clazzandstudentList.isEmpty()){
            for(Clazzandstudent clazzandstudent:clazzandstudentList){
                userIds.add(Math.toIntExact(clazzandstudent.getUserId()));
            }
            List<User> userList = userService.listByIds(userIds);

            //获取试卷数量
            QueryWrapper queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.in("userId",userIds);
            queryWrapper1.in("isComplete",1);
            List<Userexercisesetlog> userexercisesetlogList = userexercisesetlogService.list(queryWrapper1);

            //获取提问数量
            QueryWrapper queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.in("createUserId",userIds);
            List<Studentqa> studentqaList = studentqaService.list(queryWrapper2);


            //获取笔记梳理
            QueryWrapper queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.in("createUserId",userIds);
            List<Studentnote> studentnoteList = studentnoteService.list(queryWrapper3);

            //获取标记数量

            QueryWrapper queryWrapper4 = new QueryWrapper<>();
            queryWrapper4.in("createUserId",userIds);
            List<Studentsign> studentsignList = studentsignService.list(queryWrapper4);
            for(User user:userList){
                Map<String,String> map = new HashMap<>();
                map.put("id", String.valueOf(user.getId()));
                map.put("userName", user.getUsername());
                map.put("testNum", "0");
                map.put("qaNum", "0");
                map.put("noteNum", "0");
                map.put("signNum", "0");
                //绑定试卷
                for(Userexercisesetlog userexercisesetlog:userexercisesetlogList){
                    if(user.getId() == userexercisesetlog.getUserid()){
                        map.put("testNum", String.valueOf(Integer.valueOf(map.get("testNum")) + 1));
                    }
                }
                //绑定提问
                for(Studentqa studentqa:studentqaList){
                    if(user.getId() == Math.toIntExact(studentqa.getCreateUserId())){
                        map.put("qaNum", String.valueOf(Integer.valueOf(map.get("qaNum")) + 1));
                    }
                }

                //绑定标记
                for(Studentsign studentsign:studentsignList){
                    if(user.getId() == Math.toIntExact(studentsign.getCreateUserId())){
                        map.put("signNum", String.valueOf(Integer.valueOf(map.get("signNum")) + 1));
                    }
                }

                //绑定笔记
                for(Studentnote studentnote:studentnoteList){
                    if(user.getId() == Math.toIntExact(studentnote.getCreateUserId())){
                        map.put("noteNum", String.valueOf(Integer.valueOf(map.get("noteNum")) + 1));
                    }
                }

                maps.add(map);
            }

        }
        return new ResponseEntity<>(maps, HttpStatus.OK);
    }


    //查询本人拥有的课程
    public List<Integer> getCourseIds(){
        //查询教师创建课程
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("createUserId", SecurityUtils.getCurrentUserId());
        List<Course> courseList = courseService.list(queryWrapper);

        List<Integer> courseIds = new ArrayList<>();
        for(Course course:courseList){
            courseIds.add(course.getId());
        }
        return courseIds;
    }
    //查询本人拥有的班级
    public List<Integer> getClazzIds(){

        List<Integer> courseIds = getCourseIds();
        //根据课程查询班级
        List<Courseandclazz> courseandclazzList = new ArrayList<>();
        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.in("courseId",courseIds);
        if(!courseIds.isEmpty()){
            courseandclazzList = courseandclazzService.list(queryWrapper1);
        }
        List<Integer> clazzIds = new ArrayList<>();
        for(Courseandclazz courseandclazz:courseandclazzList){
            clazzIds.add(Math.toIntExact(courseandclazz.getClazzId()));
        }
        return clazzIds;
    }

    private static List<Timestamp> generateDailyTimestamps(int daysBack) {
        List<Timestamp> timestamps = new ArrayList<>();
        LocalDate today = LocalDate.now();

        for (int i = 0; i <= daysBack; i++) {
            LocalDate date = today.minusDays(i);
            LocalDateTime startOfDay = LocalDateTime.of(date, LocalDateTime.MIN.toLocalTime());

            Timestamp timestamp = Timestamp.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
            timestamps.add(timestamp);
        }

        return timestamps;
    }

    public  List<Map<String,String>> getStudentQuestionNum(){
        //获取学生用户拥有的教材
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",SecurityUtils.getCurrentUserId());
        List<Myteach> myteachList = myteachService.list(queryWrapper);
        List<Integer> teachIds = new ArrayList<>();
        for(Myteach myteach:myteachList){
            teachIds.add(myteach.getTeachId());
        }
        //获取用户教材所作的试题
        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("userId",SecurityUtils.getCurrentUserId());
        queryWrapper1.in("teachId",teachIds);
        List<Userquestionlog> userquestionlogList = new ArrayList<>();

        //获取教材
        List<Teach> teachList = new ArrayList<>();
        List<Map<String,String>> maps = new ArrayList<>();
        if(!teachIds.isEmpty()){
            teachList = teachService.listByIds(teachIds);
            for(Teach teach:teachList){
                Map<String,String> map = new HashMap<>();
                map.put("id",String.valueOf(teach.getId()));
                map.put("name",teach.getName());
                map.put("errorNum","0");
                map.put("correctNum","0");
                map.put("questionNum","0");
                maps.add(map);
            }
            userquestionlogList = userquestionlogService.list(queryWrapper1);

            for(Userquestionlog userquestionlog:userquestionlogList){
                for(Map<String,String> map:maps){
                    if(Integer.parseInt(map.get("id")) == Math.toIntExact(userquestionlog.getTeachid())){
                        if(userquestionlog.getIstrue() == 1){
                            Integer currentNum =  Integer.parseInt(map.get("correctNum")) + 1;
                            map.put("correctNum", String.valueOf(currentNum));
                        } else {
                            Integer currentNum =  Integer.parseInt(map.get("errorNum")) + 1;
                            map.put("errorNum", String.valueOf(currentNum));

                        }
                        Integer num =  Integer.parseInt(map.get("correctNum")) + Integer.parseInt(map.get("errorNum"));
                        map.put("questionNum",String.valueOf(num));
                    }
                }
            }
        }
        return maps;
    }

    //包含
    //错题列表
    public boolean containsElement(List<Integer> array, Integer target) {
        for (int i = 0; i < array.size(); i++) {
            if (array.get(i) ==  target) {
                return true;
            }
        }
        return false;
    }
}
